package com.starter.home.util;

import com.starter.home.domain.entity.User;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import java.util.Random;

/**
 * @program: manager
 * @description: 自定义工具类
 * @author: Lijian
 * @create: 2019-12-26 20:08
 */
@Component
public class MyUtil {


    /**
     * 生成token
     * @param userId
     * @return
     */
    public static String generateToken(String userId){
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] md5 = digest.digest(userId.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(md5);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return userId;
    }

    /**
     * 给指定字符串按照md5算法去加密
     * @param psd 需要加密的密码   加盐处理
     * @return md5后的字符串
     */
    public static String encoderMD5(String psd) {
        try {
            //加盐处理
            psd = psd + "mobilesafe";
            //1,指定加密算法类型
            MessageDigest digest = MessageDigest.getInstance("MD5");
            //2,将需要加密的字符串中转换成byte类型的数组,然后进行随机哈希过程
            byte[] bs = digest.digest(psd.getBytes());
            //3,循环遍历bs,然后让其生成32位字符串,固定写法
            //4,拼接字符串过程
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bs) {
                int i = b & 0xff;
                //int类型的i需要转换成16机制字符
                String hexString = Integer.toHexString(i);
                if (hexString.length() < 2) {
                    hexString = "0" + hexString;
                }
                stringBuffer.append(hexString);
            }
            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Optional<User> getUser(HttpSession session) {
        return Optional.ofNullable(((User) session.getAttribute("user")));
    }


    /**
     * 获取id
     * @param d
     */
    public String generateId(String d) {
        return d + DateUtil.getNowDate_CN() + getRandom();
    }

    /**
     * 获取位数为7位的随机数
     * @return
     * */
    public static String getRandom() {
        Random random = new Random();
        int nextInt = random.nextInt(90000);
        nextInt=nextInt+10000;
        String str=nextInt+"";
        return str;
    }
}
